-- 创建检查函数
drop function if exists check_first_5_lines_f;
CREATE OR REPLACE FUNCTION check_first_5_lines_f(
    input_text TEXT,
    search_term TEXT DEFAULT 'set search_path'
) RETURNS BOOLEAN AS $$
DECLARE
    lines TEXT[];
    i INT;
BEGIN
    -- 将字符串按换行符分割成数组
    lines := string_to_array(input_text, E'\n');

    -- 检查前5行（或实际存在的行数）
    FOR i IN 1..LEAST(5, array_length(lines, 1)) LOOP
        -- 使用正则表达式进行不区分大小写的匹配
        IF lines[i] ~* search_term THEN
            RETURN TRUE;
        END IF;
    END LOOP;

    RETURN FALSE;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- 使用示例
WITH sample_data AS (
    SELECT
        'SELECT 1;




        SET SEARCH_PATH = public
        ' AS script,
        'set search_path' AS search_term
)
SELECT
    script,
    check_first_5_lines_f(script, search_term) AS contains_set_search_path
FROM sample_data;

select check_first_5_lines_f(
'SELECT 1;




        SET SEARCH_PATH = public
        ', 'set search_path')


